# -*- coding: utf-8 -*-
#    Copyright 2005 Spike^ekipS <spikeekips@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

URL_ERROR = (-3, )
import os, urlparse, urllib
import http
def get_favicon (url, save_name, page_getter=http.pageGetterBasic) :
	try :
		if not http.validate_url(url, True) :
			return None
	except Exception, e :
		if e.reason[0] in URL_ERROR :
			return None

	(__scheme, __netloc, __path, __params, __query, __fragment, ) = \
		urlparse.urlparse(url)

	__path = os.path.dirname(__path) + "/"
	TEMPLATE_URL = "%s://%s%s"
	__p = __path
	while 1 :
		(__p, __dummy, ) = os.path.split(__p)
		if __p == os.sep and not __dummy :
			break

		if __p.strip().endswith("/") :
			__path_ico = "%sfavicon.ico" % __p
		else :
			__path_ico = "%s/favicon.ico" % __p

		__url_ico = TEMPLATE_URL % (__scheme, __netloc, __path_ico)
		(__d, __headers, ) = page_getter.get_page_new(__url_ico)
		if __headers.gettype() != "image/x-icon" :
			continue
		else :
			fd = file(save_name, "w")
			fd.write(__d)
			fd.close()
			
			return True

	return False

def convert_favicon (path_ico, path_new) :
	(o, i, e, ) = os.popen3(["/usr/bin/convert", path_ico, path_new, ])

	try :
		if len(e.readlines()) > 0 :
			return False
		else :
			return True
	except :
		return True

	 
if __name__ == "__main__" :
	url = "http://mail.google.com/mail/"
	convert_favicon("./0.ico", "./11.png")
	print get_favicon(url)


"""
Description
-----------


ChangeLog
---------


Usage
-----


"""

__author__ =  "Spike^ekipS <spikeekips@gmail.com>"
__version__=  "0.1"
__nonsense__ = ""

__file__ = "favicon.py"


